package com.frank.oj.service.admin.system.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.frank.model.entity.user.Session;
import com.frank.oj.common.result.CommonResult;
import com.frank.oj.service.admin.system.DashboardService;
import com.frank.oj.service.entity.contest.ContestEntityService;
import com.frank.oj.service.entity.judge.JudgeEntityService;
import com.frank.oj.service.entity.problem.ProblemEntityService;
import com.frank.oj.service.entity.user.SessionEntryService;
import com.frank.oj.service.entity.user.UserInfoEntityService;
import com.frank.oj.shiro.AccountProfile;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author frank
 * @Date 2024/3/27
 */
@Service
public class DashboardServiceImpl implements DashboardService {
    @Resource
    private SessionEntryService sessionEntryService;
    @Resource
    private UserInfoEntityService userInfoEntityService;
    @Resource
    private ContestEntityService contestEntityService;
    @Resource
    private JudgeEntityService judgeEntityService;
    @Resource
    private ProblemEntityService problemEntityService;
    @Override
    public CommonResult<Session> getRecentSession() {
        AccountProfile userRole = (AccountProfile) SecurityUtils.getSubject().getPrincipal();

        LambdaQueryWrapper<Session> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Session::getUid,userRole.getUid()).orderByDesc(Session::getGmtCreate);
        List<Session> sessionList = sessionEntryService.list(queryWrapper);

        // 获取最近的一个session
        if (sessionList.size()>1){
            return CommonResult.successResponse(sessionList.get(1));
        }else {
            return CommonResult.successResponse(sessionList.get(0));
        }
    }

    @Override
    public Map<Object, Object> getDashboardInfo() {
        int userNum = userInfoEntityService.count();
        int contestNum = contestEntityService.getWithinNext14DaysContest().size();
        int judgeNum=judgeEntityService.getTodayJudgeNum();
        int problemCount = problemEntityService.count();

        return MapUtil.builder()
                .put("userNum",userNum)
                .put("recentContestNum",contestNum)
                .put("todayJudgeNum",judgeNum)
                .put("problemCount",problemCount)
                .map();
    }
}
